#include <iostream>
#include <vector>
using namespace std;
/*
    kmp算法
    最好、最坏时间复杂度: O(n + m)
    空间复杂度: O(m)
*/

void getNext(vector<int>& next, const string& pat) {
    int n = pat.size();
    next[0] = -1;
    int prefix = -1, suffix = 0;
    for(int i=1;i<n;i++){
        next[i] = prefix+1;
        prefix++, suffix++;
        while(prefix != -1 && pat[prefix] != pat[suffix]) prefix = next[prefix];
    }
}

void getNextVal(vector<int>& nextVal, const string& pat) {
    int n = pat.size();
    nextVal[0] = -1;
    int prefix = -1, suffix = 0;
    for(int i=1;i<n;i++){
        nextVal[i] = prefix+1;
        while(nextVal[i] != -1 && pat[i] == pat[nextVal[i]]) nextVal[i] = nextVal[nextVal[i]];
        prefix++, suffix++;
        while(prefix != -1 && pat[prefix] != pat[suffix]) prefix = nextVal[prefix];
    }
}

int kmp(string txt, string pat) {
    vector<int> next(pat.size());
    getNextVal(next, pat);
    int i = 0, j = 0;
    while (i < txt.size()) {
        if (j == -1 || txt[i] == pat[j]) {
            i++, j++;
            if (j == pat.size()) return i - j;
        } else {
            j = next[j];
        }
    }
    return -1;
}